package com.zhigh.project.security.jwt.authentication;

import com.zhigh.project.security.jwt.authentication.exception.JWTAuthenticationException;
import com.zhigh.project.tools.Assertions;

public class JWTAuthenticationProvider extends AbstractJWTAuthenticationProvider {

    private SecretHolder<JWT> secretHolder;

    public JWTAuthenticationProvider(SecretHolder<JWT> secretHolder) {
        this.secretHolder = secretHolder;
    }

    @Override
    protected String getSecret(JWT jwt) {
        return secretHolder.getSecret(jwt);
    }

    @Override
    protected void doAfterPropertiesSet() throws Exception {
        super.doAfterPropertiesSet();
        Assertions.assertNonnull(secretHolder, messages.getMessage("JWTAuthenticationProvider.secretHolder.isnull",
                "SecretHolder<JWT> is null."));
    }

    public SecretHolder<JWT> getSecretHolder() {
        return secretHolder;
    }


    @Override
    protected void additionalAuthenticate(JWTAuthentication token) {
        JWT jwt = token.getPrincipal().getJwt();
        if (!jwt.verify(getSecret(jwt))) {
            throw new JWTAuthenticationException("TOKEN无效");
        }
    }

    public void setSecretHolder(SecretHolder<JWT> secretHolder) {
        this.secretHolder = secretHolder;
    }
}
